package zserver

import (
	"fmt"
	"net"
	"zinx/utils"
	"zinx/zinterface"
)

type ZConnector struct {
	ConnId   uint32             // 1. id
	Conn     *net.TCPConn       // 2. socket套接字
	isClosed bool               // 3. 当前的状态
	Router   zinterface.IRouter // 路由
	ExitChan chan bool          // 5. 等待连接推出的channel

}

func NewConnector(conn *net.TCPConn, id uint32, router zinterface.IRouter) *ZConnector {
	zc := &ZConnector{
		ConnId:   id,
		Conn:     conn,
		isClosed: false,
		ExitChan: make(chan bool, 1),
		Router:   router,
	}

	return zc
}

/*
	实现iconnector接口
*/

func (zc *ZConnector) StartReader() {
	fmt.Println("Reader goroutine is running...")
	defer fmt.Println("Connection: ", zc.ConnId, " is STOPPING, RemoteAddr is: ", zc.Conn.RemoteAddr().String())
	defer zc.Stop()

	for {
		// 读取客户端发送的字节
		buf := make([]byte, utils.GlobalObject.MaxPackageSize)
		_, err := zc.Conn.Read(buf)
		if err != nil {
			fmt.Println("!!!ERROR When Reading From Client: ", err)
			zc.ExitChan <- true
			continue
		}

		req := &ZRequest{
			conn: zc,
			data: buf,
		}

		//调用router中的处理方法
		go func(request	zinterface.IRequest) {
			zc.Router.PreHandle(request)
			zc.Router.Handle(request)
			zc.Router.PostHandle(request)
		}(req)

	}

}

func (zc *ZConnector) Start() {
	fmt.Println("START CONNECTION: ", zc.ConnId)

	// 启动读goroutine
	go zc.StartReader()

	// TODO: 启动写goroutine

}

func (zc *ZConnector) Stop() {
	fmt.Println("Start STOP CONNECTION: ", zc.ConnId)

	if zc.isClosed {
		fmt.Println("CONNECTION ", zc.ConnId, " has already closed!")
		return
	}

	// 关闭连接，释放资源
	zc.isClosed = true

	zc.Conn.Close()

	close(zc.ExitChan)
}

func (zc *ZConnector) GetTCPConnection() *net.TCPConn {
	return zc.Conn
}

func (zc *ZConnector) GetRemoteAddr() net.Addr {
	return zc.Conn.RemoteAddr()
}

func (zc *ZConnector) GetId() uint32 {
	return zc.ConnId
}

func (zc *ZConnector) IsClosed() bool {
	return zc.isClosed
}

func (zc *ZConnector) Send([]byte) error {
	// TODO:
	return nil
}
